package ajax;

import Impl.plateDaoImpl;
import com.alibaba.fastjson.JSON;
import dao.userDao;
import entity.Plate;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

//@WebServlet(name = "FatherAndChildAjax", urlPatterns = "/findAjax")
public class FatherAndChildAjax extends HttpServlet {

    plateDaoImpl plateDao = new plateDaoImpl();
    ArrayList<Plate> fatherSectionList = (ArrayList<Plate>) plateDao.findPlateByPId(0);
    ArrayList<Plate> childSectionList = plateDao.findAllChildPlate();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("-----正在执行findAjax----------");
        String method = request.getParameter("method");
        if (null != method && !"".equals(method))
        {
            if ("initFather".equals(method))
            {
                initFather(request, response);
            } else if ("getChild".equals(method))
            {
                getChild(request, response);
            }
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void initFather(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html; charset=UTF-8");
        response.setCharacterEncoding("utf-8");
        String fatherStr = JSON.toJSONString(fatherSectionList);
        response.getWriter().write(fatherStr);
    }
    protected void getChild(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html; charset=UTF-8");
        response.setCharacterEncoding("utf-8");
        System.out.println("输出sId");
        int sId = Integer.parseInt(request.getParameter("sId"));
        System.out.println("FatherAndChildAjax.java: sId: " + sId);
        ArrayList<Plate> tmpList = new ArrayList<>();
        for (int i = 0; i < childSectionList.size(); i++) {
            if (childSectionList.get(i).getsParentId() == sId) {
                tmpList.add(childSectionList.get(i));
                System.out.println("FatherAndChildAjax.java: " + childSectionList.get(i).toString());
            }
        }
        if (tmpList.size()==0){
            List<Plate> plateByPId = plateDao.findPlateBySid(sId);
            tmpList.add(plateByPId.get(0));
        }
        String childStr = JSON.toJSONString(tmpList);
        response.getWriter().write(childStr);
        System.out.println("FatherAndChildAjax.java: getChildSuccess");
    }


}
